import { AutoComplete, Card, Checkbox, Col, Empty, Input, Spin } from 'antd';
import {
  ChangeEvent,
  useCallback,
  useContext,
  useEffect,
  useMemo,
  useState,
} from 'react';
import { IAuthSecondRightCard } from '../../type';
import { AuthorizationContext } from '../AuthHooks';
import { SearchOutlined } from '@ant-design/icons';
import ScrollBarLayout from '@/components/ScrollBarLayout';
import MyIcon from '@/components/MyIcon';
import { deepClone, loopArray } from '@/utils';

export const AuthSecondRightCard: React.FC<IAuthSecondRightCard> = ({
  secondRightData,
  defaultSecIDList,
  leftDataTree,
}) => {
  const { prefixCls, secondRightSearchValue, authGranDispatch } = useContext(
    AuthorizationContext,
  ); //获取 上下文

  const [defaultCheckIDS, setDefaultCheckIDS] = useState<any>(null); //保存 选中的id
  const defaCheckCallback = useCallback(
    (idsArr: any[]) => {
      setDefaultCheckIDS(idsArr);
      if (idsArr != null) {
        authGranDispatch({
          type: 'authGran-secondSaveIdList',
          payload: idsArr,
        });
      } else {
        authGranDispatch({
          type: 'authGran-secondSaveIdList',
          payload: null,
        });
      }
    },
    [defaultCheckIDS],
  );

  useEffect(() => {
    defaCheckCallback(defaultSecIDList);
  }, [defaultSecIDList]);

  // 搜索下拉菜单
  const autoOptionRight = useMemo(() => {
    let option: Record<string, any>[] = [];
    const tileTreeData = (data: Record<string, any>[]) => {
      data?.forEach((item) => {
        if ((item?.text || item?.name)?.includes(secondRightSearchValue)) {
          // const name = item?.text || item?.name;
          // const nameLength = name?.length;
          // const select = name?.search(secondRightSearchValue);
          // const searchLength = secondRightSearchValue?.length;
          // const afterStr = name?.slice(0, select);
          // const selectStr = secondRightSearchValue;
          // const beforeStr = name?.slice(select + searchLength, nameLength);
          option.push({
            value: item?.text || item?.name,
            key: item?.id,
            // label: (
            //   <div>
            //     <span>{afterStr}</span>
            //     <span style={{ color: '#f50' }}>{selectStr}</span>
            //     <span>{beforeStr}</span>
            //   </div>
            // ),
          });
        }
      });
    };
    tileTreeData(secondRightData?.dataSource);
    return option;
  }, [secondRightData?.dataSource, secondRightSearchValue]);

  // 处理搜索变色
  const searchChangeStyle = (itemObj: Record<string, any>) => {
    const name = itemObj?.name || itemObj?.text;
    const nameLength = name?.length;
    const select = name?.search(secondRightSearchValue);
    const searchLength = secondRightSearchValue?.length;
    const afterStr = name?.slice(0, select);
    const selectStr = secondRightSearchValue;
    const beforeStr = name?.slice(select + searchLength, nameLength);
    const title =
      select > -1 && selectStr ? (
        <div id={itemObj?.id + 'rightCard'}>
          <MyIcon type={itemObj?.icon} />
          &nbsp;
          {afterStr}
          <span style={{ color: '#f50' }}>{selectStr}</span>
          {beforeStr}
        </div>
      ) : (
        <div id={itemObj?.id + 'rightCard'}>
          <MyIcon type={itemObj?.icon} />
          &nbsp;
          {itemObj?.name || itemObj?.text}
        </div>
      );
    return title;
  };

  // 点击搜索
  const onAutoSelect = (value: string, option: any) => {
    const promise = new Promise((resolve) => {
      const optionId = option?.key;
      authGranDispatch({
        type: 'authGran-secondRightSearchValue',
        payload: value,
      });

      setTimeout(() => {
        scrollToAnchor(optionId);
      }, 1000);

      resolve(optionId);
    });
    promise.then((res: any) => {
      if (res) {
      }
    });
  };

  // 滚动定位
  const scrollToAnchor = (id: string) => {
    let anchorElement = document.getElementById(id + 'rightCard');
    if (id) {
      anchorElement?.scrollIntoView({
        behavior: 'smooth',
        block: 'nearest',
        inline: 'start',
      });
    }
  };

  // 搜索框改变
  const onInputChange = (e: ChangeEvent<HTMLInputElement>) => {
    authGranDispatch({
      type: 'authGran-secondRightSearchValue',
      payload: e.target.value,
    });
  };

  // 多选框点击方法
  const checkOnChange = (e: any, checkObj: Record<string, any>) => {
    let checkBool = e?.target?.checked;
    let pushCheck = ifChildren(checkObj, checkBool);
    defaCheckCallback([...pushCheck]);
  };

  // 选中后判断是目录还是菜单, 如果是目录则全选子集, 如果不是则单选带上父级
  const ifChildren = (obj: Record<string, any>, addOrDel: boolean) => {
    let checkIDS = defaultCheckIDS ? deepClone(defaultCheckIDS) : [];
    let checkKey: any[] = []; //用于取消全选的时候 单独保存点击的参数
    if (obj?.children?.length > 0) {
      let tileCheckList = loopArray([obj]);
      tileCheckList?.map((item) => {
        checkIDS?.push(item?.id);
        checkKey?.push(item?.id);
      });
      if (!addOrDel) {
        checkIDS = defaultCheckIDS.filter((itemIds: any) => {
          return !checkKey?.includes(itemIds);
        });
      }
    } else {
      checkIDS?.push(obj?.pID, obj?.id);
      if (!addOrDel) {
        checkIDS = defaultCheckIDS.filter((itemIds: any) => {
          return itemIds != obj?.id;
        });
      }
    }
    let removalIDS = [...new Set(checkIDS)];
    let handleIDS = handleNoChildren(removalIDS, obj);
    return handleIDS;
  };

  // 处理当子节点全部没有选中时候,去除父节点选中效果
  const handleNoChildren = (idList: any[], onObj: any) => {
    let isHaveChild: any = [];
    let loopTree = (dataList: any) => {
      dataList?.forEach((item: any) => {
        if (onObj?.pID == item?.id) {
          isHaveChild = item?.children?.filter((itemChild: any) => {
            return idList?.includes(itemChild?.id);
          });
        }
      });
    };
    loopTree(secondRightData?.dataSource);
    if (isHaveChild && isHaveChild?.length > 0) {
      return idList;
    } else {
      return idList?.filter((itemObj: any) => {
        return itemObj != onObj?.pID;
      });
    }
  };

  return (
    <Col span={18} className={prefixCls + 'step-cardRole-rightColCard'}>
      {leftDataTree?.length <= 0 ? (
        <>
          <Empty
            style={{ paddingTop: '15%' }}
            image={Empty.PRESENTED_IMAGE_SIMPLE}
          />
        </>
      ) : (
        <>
          {secondRightData?.tableLoading ? (
            <Spin spinning={true} style={{ height: '100%', width: '100%' }}>
              <Empty
                style={{ paddingTop: '15%' }}
                image={Empty.PRESENTED_IMAGE_SIMPLE}
              />
            </Spin>
          ) : (
            <>
              <div
                style={{
                  width: '100%',
                  display: 'flex',
                  justifyContent: 'flex-end',
                }}
              >
                <AutoComplete
                  style={{ width: '50%', height: '5%' }}
                  options={autoOptionRight}
                  notFoundContent={
                    <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
                  }
                  onSelect={onAutoSelect}
                >
                  <Input
                    suffix={<SearchOutlined />}
                    onChange={onInputChange}
                    placeholder="请按名称搜索"
                    allowClear={true}
                  />
                </AutoComplete>
              </div>
              <ScrollBarLayout style={{ height: '90%', paddingTop: 10 }}>
                {secondRightData?.dataSource?.length > 0 ? (
                  <div className={prefixCls + 'rightCardAuthThree'}>
                    {secondRightData?.dataSource?.map((item: any) => {
                      return (
                        <div key={item?.id + 'rightCardTitle'}>
                          <Card
                            bordered
                            title={
                              <Checkbox
                                checked={
                                  defaultCheckIDS?.includes(item?.id)
                                    ? true
                                    : false
                                }
                                onChange={(event: any) => {
                                  checkOnChange(event, item);
                                }}
                                key={item?.id}
                              >
                                {searchChangeStyle(item)}
                              </Checkbox>
                            }
                          >
                            <ScrollBarLayout
                              style={{
                                padding: '10px 10px',
                                height: document.body.clientHeight * 0.2,
                              }}
                            >
                              {item?.children?.length > 0 ? (
                                <div
                                  className={
                                    prefixCls + 'rightCardAuthThree-detailCard'
                                  }
                                >
                                  {item?.children?.map((itemChildren: any) => {
                                    return (
                                      <div
                                        className={
                                          prefixCls +
                                          'rightCardAuthThree-detailCardChild'
                                        }
                                        id={itemChildren?.id}
                                        key={itemChildren?.id}
                                      >
                                        <Checkbox
                                          checked={
                                            defaultCheckIDS?.includes(
                                              itemChildren?.id,
                                            )
                                              ? true
                                              : false
                                          }
                                          key={itemChildren?.id}
                                          onChange={(event: any) => {
                                            checkOnChange(event, itemChildren);
                                          }}
                                        >
                                          {itemChildren?.name ||
                                            itemChildren?.text}
                                        </Checkbox>
                                      </div>
                                    );
                                  })}
                                </div>
                              ) : (
                                <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
                              )}
                            </ScrollBarLayout>
                          </Card>
                        </div>
                      );
                    })}
                  </div>
                ) : (
                  <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
                )}
              </ScrollBarLayout>
            </>
          )}
        </>
      )}
    </Col>
  );
};
